package servlet;

import core.Note;
import core.Noteboard;
import core.User;
import java.io.*;
import java.util.ArrayList;
import java.util.logging.*;
import javax.annotation.Resource;
import javax.persistence.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.xml.sax.SAXException;

/**
 *
 * @author Keith
 */
public class NoteboardServlet extends HttpServlet {
    @PersistenceUnit
    EntityManagerFactory emf;
    @Resource
    private UserTransaction utx;

    ArrayList<Note> notes = new ArrayList<Note>();
    private String userID = "POLEN";

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = response.getWriter();

        try {
            if (request.getMethod().equals("GET")) {
                System.out.println("GET");
                System.out.print(javaToXML(notes));
                out.print(javaToXML(notes));
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        try {
            DocumentBuilder db = (DocumentBuilderFactory.newInstance()).newDocumentBuilder();
            Document doc = db.parse(request.getInputStream());
            Element notesElement = doc.getDocumentElement();
            System.out.println("POST");
            writeXmlFile(doc, "c:\\keith\\test.xml");
            NodeList noteList = notesElement.getChildNodes();
            notesFromXML(noteList);
            User u = new User(userID);
            u.setFirstname("Bill");
            u.setLastname("Gates");
            u.setEmail("bill@microsoft.com");
            Noteboard n = new Noteboard(userID, "LITEN");
            n.setXml(javaToXML(notes));
            out.print(javaToXML(notes));
            saveNoteboard(u,n);
        } catch (SecurityException ex) {
            Logger.getLogger(NoteboardServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalStateException ex) {
            Logger.getLogger(NoteboardServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(NoteboardServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(NoteboardServlet.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
//        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>

    public boolean saveNoteboard(User u, Noteboard n) {
        try {
            utx.begin();
            EntityManager em = emf.createEntityManager();
            em.persist(u);
            em.persist(n);
            utx.commit();
            return true;
        } catch (javax.transaction.RollbackException ex) {
            Logger.getLogger(NoteboardServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (HeuristicMixedException ex) {
            Logger.getLogger(NoteboardServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (HeuristicRollbackException ex) {
            Logger.getLogger(NoteboardServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            Logger.getLogger(NoteboardServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalStateException ex) {
            Logger.getLogger(NoteboardServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NotSupportedException ex) {
            Logger.getLogger(NoteboardServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SystemException ex) {
            Logger.getLogger(NoteboardServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }

    private void notesFromXML(NodeList nl) {
        notes.clear();
        for (int i = 0; i < nl.getLength(); i++) {
            notes.add(Note.noteFromNode(nl.item(i)));
        }
    }

    private String notesToString(NodeList nl) {
        String res = "";
        for (int i = 0; i < nl.getLength(); i++) {
            Note.noteFromNode(nl.item(i));
        }
        return res;
    }

    private String javaToXML(ArrayList<Note> notes) {
        String noteHead = "<notes>";
        for (int i = 0; i < notes.size(); i++) {
            noteHead += notes.get(i).toXML();
        }
        noteHead += "</notes>";
        return noteHead;
    }

    private static void writeXmlFile(Document doc, String filename) {
        try {
            // Prepare the DOM document for writing
            Source source = new DOMSource(doc);

            // Prepare the output file
            File file = new File(filename);
            Result result = new StreamResult(file);

            // Write the DOM document to the file
            Transformer xformer = TransformerFactory.newInstance().newTransformer();
            xformer.transform(source, result);
        } catch (TransformerConfigurationException e) {
            Logger.getLogger(NoteboardServlet.class.getName()).log(Level.SEVERE, null, e);
        } catch (TransformerException e) {
            Logger.getLogger(NoteboardServlet.class.getName()).log(Level.SEVERE, null, e);
        }
    }
}
